<?php
namespace App\Services;

use JPush\Client as JPush;
use Illuminate\Support\Facades\Log;

class JPushService
{
    const APPKEY = '82fe5dc2aa7108e1cb921c86';
    const APPSECRET = '87fff1d9eb117750a5513004';

    /**
     * @created 在 2021/12/21 16:07 创建
     * @param $receiver 接收者的信息(用户id)
     * @param $alert 表示通知内容，会覆盖上级统一指定的 alert 信息；默认内容可以为空字符串，表示不展示到通知栏, 支持字符串和数组两种形式
     * @param $extras 表示扩展字段，接受一个数组，自定义 Key/value 信息以供业务使用
     * @author: Sun Wu
     */
    public static function push($alert, $extras, $receiver)
    {
        $client = new JPush(SELF::APPKEY, SELF::APPSECRET);
        try {
            $response = $client->push()
                ->addAlias($receiver)
                ->setPlatform('all')     //平台
                ->setNotificationAlert($alert)        //简单地给所有平台推送相同的 alert 消息
                ->iosNotification($alert, [           //ios 消息
                    'extras' => $extras
                ])
                ->androidNotification($alert, [       //安卓消息
                    'extras' => $extras
                ])
                ->message($alert, [
                    'title' => $alert,
                    'content_type' => 'text',
                    'extras' => $extras
                ])
                ->send();
            Log::debug('jpush:'.var_export($response, true));
            return true;
        } catch (\JPush\Exceptions\APIConnectionException $e) {
            // try something here
            print $e;
        } catch (\JPush\Exceptions\APIRequestException $e) {
            // try something here
            print $e;
        }

    }
}
